
// var table = document.getElementById("#depTable")
var ul = document.getElementsByClassName("pagination")[0];
var pageSize = 5;

var fragment1;
var currentPage = 1;
var totalPages, liAll, pre, next, start, end, clickPage;


$(document).ready(function () {

    disData(clickPage);
    addData();
    disPage();
    resetBtnEvent();
    addDelEvent();

    addEditEvent();
    selDataById();
    // init();
});

// 显示数据
function disData() {
    console.log(db.performance);
    // 获取点击的页码数据，如果不为Undefined，那么将点击的页码按钮的值赋给当前页变量
    if (clickPage != undefined) {
        currentPage = clickPage;
    }
    // 如果当前页!=1，数据开始和结束的位置赋值
    if (currentPage != 1) {
        start = (currentPage - 1) * pageSize;
        end = start + pageSize - 1;
    } else {
        start = 0;
        end = pageSize - 1;
    }
    // 清空数据列表的内容
    $("#depTable").html("");
    for (let i = 0; i < db.performance.length; i++) {
        // 创建文档碎片
        let fragment1 = document.createDocumentFragment();
        // 如果数据下标>=start并且<=end并且小于数组的长度
        if (i >= start && i <= end && i < db.performance.length) {
            let tr = document.createElement("tr");
            tr.innerHTML = `
                <input type="hidden" value='${db.performance[i].id}'>
                <td>${db.performance[i].name}</td>
                <td>${db.performance[i].departmentName}</td>
                <td>${db.performance[i].oYear}</td>
                <td>${db.performance[i].KPI}</td>
                <td>${db.performance[i].firstQuarter}</td>
                <td>${db.performance[i].secondQuarter}</td>
                <td>${db.performance[i].thirdQuarter}</td>
                <td>${db.performance[i].forthQuarter}</td>
                <td>${db.performance[i].remarks}</td>
                <td>
                    <button class='btnEdit' data-target="#pfmEditModal" data-toggle="modal" id="edit" onclick="showDialog(this)">编辑</button>
                    <button class='btnDel' data-target="#pfmDelModal" data-toggle="modal">删除</button>
                </td>
            `
            fragment1.appendChild(tr);
        }
        $("#depTable").append(fragment1);
    }
    // 调用上一页下一页事件函数
    // prevBtn(currentPage);


}

// 分页显示数据
function disPage(total) {
    // 设置数据总长度为数据表的数据长度
    if (total == undefined) {
        var total = db.performance.length;
    } else {
        total = total;
        console.log(total);
    }
    // 如果总长度%每页显示的数据数==0（能整除）  总页数=总长度%每页显示数据   否则除下的数+1（向上取整）
    totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
    // 清空页码列表
    ul.innerHTML = '';
    let aab = '';
    for (let i = 1; i <= totalPages; i++) {
        if (i == currentPage) {
            aab += `<li id="${i}" class='active'><a href="#" class='clipgbtn'>${i}</a></li>`
        } else {
            aab += `<li id="${i}"><a href="#"  class='clipgbtn'>${i}</a></li>`
        }
    }
    // 往页码列表中添加内容
    ul.innerHTML += `
    <li id="pre">
        <a href="" class="leftColor">
            <span  class="leftColor">&lt;</span>
        </a>
    </li>
    ${aab}
    <li id="next">
            <a class="leftColor">
                <span  class="leftColor">&gt;</span>
            </a>
        </li>
    `

    ul.innerHTML += `
        
    `;
    // 设置默认页码1为活动样式
    $(".pagination li ").eq(1).addClass("active");
    $(".pagination li .clipgbtn").click(function (e) {
        e.preventDefault();
        clickPage = $(this).parent().attr('id');
        $(this).parent().addClass('active').siblings().removeClass('active');
        disData(clickPage);
    })
}


// 根据部门编码查询数据
function selDataById() {
    let data1 = [];
    let data2 = [];
    let data3 = [];


    $("#selBtn").click(function () {
        $("#depTable").html("");

        for (let i = 0; i < db.performance.length; i++) {
            if (db.performance[i].oYear == $("#depIdInput").val()) {
                data1.push(db.performance[i]);
            }
        }

        console.log(data1);
        if ($("#depNameInput").val().trim() == '') {
            data2 = data1;
        } else {
            for (let i = 0; i < data1.length; i++) {
                if (data1[i].departmentName == $("#depNameInput").val()) {
                    data2.push(data1[i]);
                }

            }
        }
        console.log(data2);

        if ($("#depPersonInput").val().trim() == '') {
            data3 = data2;
        } else {
            for (let i = 0; i < data2.length; i++) {
                if (data2[i].name == $("#depPersonInput").val()) {
                    data3.push(data2[i]);
                }
            }
        }
        $(".pagination").html("");
        let fragment1 = document.createDocumentFragment();
        for (let i = 0; i < data3.length; i++) {
            // console.log(data3[i].name);
            let tr = document.createElement("tr");
            tr.innerHTML = `
            <input type="hidden" value='${data3[i].id}'>
                <td>${data3[i].name}</td>
                <td>${data3[i].oYear}</td>
                <td>${data3[i].KPI}</td>
                <td>${data3[i].firstQuarter}</td>
                <td>${data3[i].secondQuarter}</td>
                <td>${data3[i].thirdQuarter}</td>
                <td>${data3[i].forthQuarter}</td>
                <td>${data3[i].remarks}</td>
                <td>
                    <button class='btnEdit' data-target="#pfmEditModal" data-toggle="modal" id="edit"  >编辑</button>
                    <button class='btnDel' data-target="#pfmDelModal" data-toggle="modal">删除</button>
                </td>
            `
            fragment1.appendChild(tr);
        }
        $("#depTable").append(fragment1);
        // disPage(data3.length)
        // disData(data3);

    })
}

// 重置按钮事件
function resetBtnEvent() {
    $("#resetBtn").click(function () {
        $("#depIdInput").val("");
        $("#depNameInput").val("");
        $("#depPersonInput").val("");
        disPage(db.performance.length);
        disData()
    })
}

function showDialog(obj) {
    var tds = $(obj).parent().parent().children()
    console.log($(tds.eq(0)).text());
    $("#oYear").val($(tds.eq(3)).text());
    $("#uname").val($(tds.eq(1)).text());
    $("#udepartmentName").val($(tds.eq(2)).text());
    $("#KPI").val($(tds.eq(4)).text());
    $("#firstQuarter").val($(tds.eq(5)).text());
    $("#secondQuarter").val($(tds.eq(6)).text());
    $("#thirdQuarter").val($(tds.eq(7)).text());
    $("#forthQuarter").val($(tds.eq(8)).text());
    $("#remarks").val($(tds.eq(9)).text());
}


// 修改数据事件
function addEditEvent() {
    let id;
    $("#depTable").on("click", ".btnEdit", function (e) {
        id = $(this).parent().parent().children().first().val();
        console.log('id', id);
    })
    $("#pfmsaveEditBtn").click(function (e) {
        let result = editData(id);
        if (result) {
            console.log("success");
            disPage(performance.length)
            disData()

        } else {
            console.log("default");
        }
    })
}

// 修改数据处理函数
function editData(id, name, departmentName, oYear, KPI, firstQuarter, secondQuarter, thirdQuarter, forthQuarter, remarks) {
    try {
        for (let i = 0; i < db.performance.length; i++) {
            if (db.performance[i].id == id) {
                db.performance[i].name = $("#uname").val();
                db.performance[i].oYear = $("#oYear").val();
                db.performance[i].departmentName = $("#udepartmentName").val();
                db.performance[i].KPI = $("#KPI").val();
                db.performance[i].firstQuarter = $("#firstQuarter").val();
                db.performance[i].secondQuarter = $("#secondQuarter").val();
                db.performance[i].thirdQuarter = $("#thirdQuarter").val();
                db.performance[i].forthQuarter = $("#forthQuarter").val();
                db.performance[i].remarks = $("#remarks").val();
            }
        }
        $("#pfmEditModal").modal('hide');
        asyncLocalStory("performance");
        return true;
    } catch (e) {
        return false;
    }
}

// 删除数据事件
function addDelEvent() {
    $("#depTable").on("click", ".btnDel", function (e) {
        let id = $(this).parent().parent().children().first().val();
        console.log('id', id);
        $("#pfmSaveDelBtn").click(function (e) {
            console.log(1);
            let result = delData(id);
            if (result) {
                console.log("success");
                $("#depTable").html("")
                $(".pagination").html("")
                disPage();
                disData();
            }
            else {
                console.log("default");
            }
        })
    })
}

// 删除数据处理函数
function delData(id) {
    try {
        for (let i = 0; i < db.performance.length; i++) {
            if (db.performance[i].id == id) {
                db.performance.splice(i, 1);
                console.log(db.performance);
            }
        }

        asyncLocalStory("performance");
        $("#pfmDelModal").modal('hide');
        return true;
    } catch (e) {
        return false;
    }
}

// 添加数据函数
function addData(id, name, departmentName, oYear, KPI, firstQuarter, secondQuarter, thirdQuarter, forthQuarter, remarks) {
    $("#pfmsaveAddBtn").click(function (e) {
        let id1 = 0;
        //id自增
        for (let i = 0; i < performance.length; i++) {
            if (id1 < performance[i].id) {
                id1 = performance[i].id;
            }
        }
        id1++;
        id = id1;
        name = $("#addname").val();
        oYear = $("#addoYear").val();
        departmentName = $("#adddepartmentName").val();
        KPI = $("#addKPI").val();
        firstQuarter = $("#addfirstQuarter").val();
        secondQuarter = $("#addsecondQuarter").val();
        thirdQuarter = $("#addthirdQuarter").val();
        forthQuarter = $("#addforthQuarter").val();
        remarks = $("#addremarks").val();
        // console.log(id);
        db.performance.push({ id, name, departmentName, oYear, KPI, firstQuarter, secondQuarter, thirdQuarter, forthQuarter, remarks });
        asyncLocalStory("performance");
        $("#pfmAddModal").modal('hide');
        ul.innerHTML = ""
        disPage();

    })
}

// 初始化数据
function init() {
    $(".initBtn").click(function () {
        for (let key in db) {
            localStorage.setItem(key, JSON.stringify(db[key]));
            console.log(2);
            disData()
            // console.log(JSON.stringify(db[key]));
        }
    })
}

